import axios from "../../lib/axios";

/*
 * @Author: worldzb 
 * @Date: 2019-01-08 09:30:54 
 * @Last Modified by: worldzb
 * @Last Modified time: 2019-01-14 15:14:04
 */

class Auth{
    //构造单例
    constructor(){
       if(!Auth.instance){
            this.init();
            Auth.instance=this;
       }
       return Auth.instance;
    }

    //静态单例获取
    static getInstance(){
        if(!Auth.instance){
            Auth.instance=new Auth();
        }
        return Auth.instance;
    }

    init(){
        this.username='';
        this.password='';
        this.user='';
        this.token='';
    }

    login(username,password,callback){
        
        this.username=username;
        this.password=password;
        axios.post(config.PATH+'login',{
            email:username,
            password:password
        }).then(res=>{
            if(res.data.token){
                localStorage.setItem('token',res.data.token.original.access_token);
                this.user=res.data.user;
                this.token=res.data.token;
            }
            if(typeof callback == 'function'){
                callback(res);
            }
        })

    }

    logout(callback){
        axios.post(config.PATH+'logout').then(res=>{
            if(res.data.status==200){
                localStorage.removeItem('token');
            }
            if(typeof callback == 'function'){
                callback(res);
            }
        })
    }
    
    refresh(callback){
        axios.post(config.PATH+'refresh').then(res=>{
            if(res.data.token){
                localStorage.setItem('token',res.data.token.original.access_token);
            }
            if(typeof callback == 'function'){
                callback(res);
            }
        })
    }

}

export default Auth;
